import os
import shutil
from sqlalchemy.orm import Session
from datetime import datetime

from db.models import CompilationHistory, CompilationFile
from api.schemas.compile import CompileOptions
from api.schemas.history import HistoryItem, HistoryListResponse, HistoryDetailResponse
from utils.file_handling import get_file_size
from loguru import logger

def get_compilation_history(db: Session, skip: int = 0, limit: int = 10, status: str = None):
    """获取编译历史记录列表"""
    query = db.query(CompilationHistory)
    
    # 根据状态筛选
    if status:
        query = query.filter(CompilationHistory.status == status)
    
    # 按创建时间降序排列
    query = query.order_by(CompilationHistory.created_at.desc())
    
    # 获取总数
    total = query.count()
    
    # 获取分页数据
    history_items = query.offset(skip).limit(limit).all()
    
    # 构建响应数据
    items = []
    for item in history_items:
        # 获取输入文件
        input_files = db.query(CompilationFile).filter(
            CompilationFile.history_id == item.id,
            CompilationFile.is_source == True
        ).all()
        
        # 获取输出文件
        output_files = None
        if item.status == "success":
            output_files = db.query(CompilationFile).filter(
                CompilationFile.history_id == item.id,
                CompilationFile.is_source == False
            ).all()
        
        # 创建编译选项对象
        options = CompileOptions(
            optimize=item.optimize_level,
            python_version=item.python_version,
            platform=item.platform,
            keep_source=item.keep_source,
            zip_output=item.zip_output,
            delete_temp=item.delete_temp,
            extra_args=item.extra_args,
            output_dir=item.output_dir
        )
        
        # 添加到结果列表
        items.append(HistoryItem(
            task_id=item.task_id,
            status=item.status,
            created_at=item.created_at,
            completed_at=item.completed_at,
            options=options,
            input_files=[
                {"filename": f.original_filename, "filesize": f.original_filesize}
                for f in input_files
            ],
            output_files=[
                {"filename": f.output_filename, "filesize": f.output_filesize}
                for f in output_files
            ] if output_files else None,
            error_message=item.error_message
        ))
    
    return HistoryListResponse(total=total, items=items)

def get_compilation_history_detail(db: Session, task_id: str):
    """获取编译历史记录详情"""
    history = db.query(CompilationHistory).filter(
        CompilationHistory.task_id == task_id
    ).first()
    
    if not history:
        return None
    
    # 获取输入文件
    input_files = db.query(CompilationFile).filter(
        CompilationFile.history_id == history.id,
        CompilationFile.is_source == True
    ).all()
    
    # 获取输出文件
    output_files = None
    if history.status == "success":
        output_files = db.query(CompilationFile).filter(
            CompilationFile.history_id == history.id,
            CompilationFile.is_source == False
        ).all()
    
    # 创建编译选项对象
    options = CompileOptions(
        optimize=history.optimize_level,
        python_version=history.python_version,
        platform=history.platform,
        keep_source=history.keep_source,
        zip_output=history.zip_output,
        delete_temp=history.delete_temp,
        extra_args=history.extra_args,
        output_dir=history.output_dir
    )
    
    # 获取编译日志（在实际实现中，日志可能存储在文件或数据库中）
    log_content = ""  # 这里应该从实际存储位置获取日志
    
    return HistoryDetailResponse(
        item=HistoryItem(
            task_id=history.task_id,
            status=history.status,
            created_at=history.created_at,
            completed_at=history.completed_at,
            options=options,
            input_files=[
                {"filename": f.original_filename, "filesize": f.original_filesize}
                for f in input_files
            ],
            output_files=[
                {"filename": f.output_filename, "filesize": f.output_filesize}
                for f in output_files
            ] if output_files else None,
            error_message=history.error_message
        ),
        log=log_content
    )

def delete_compilation_history(db: Session, task_id: str):
    """删除指定的历史记录"""
    history = db.query(CompilationHistory).filter(
        CompilationHistory.task_id == task_id
    ).first()
    
    if not history:
        return False
    
    # 删除相关文件
    try:
        # 删除上传的文件
        upload_dir = os.path.join("uploads", task_id)
        if os.path.exists(upload_dir):
            shutil.rmtree(upload_dir)
        
        # 删除输出文件
        output_dir = os.path.join("outputs", task_id)
        if os.path.exists(output_dir):
            shutil.rmtree(output_dir)
    except Exception as e:
        logger.warning(f"删除历史记录文件失败: {str(e)}")
    
    # 从数据库删除记录
    db.delete(history)
    db.commit()
    
    return True

def clear_all_history(db: Session):
    """清空所有历史记录"""
    # 删除所有历史记录
    db.query(CompilationHistory).delete()
    db.commit()
    
    # 删除相关文件
    try:
        # 删除上传目录
        if os.path.exists("uploads"):
            for item in os.listdir("uploads"):
                item_path = os.path.join("uploads", item)
                if os.path.isdir(item_path):
                    shutil.rmtree(item_path)
        
        # 删除输出目录
        if os.path.exists("outputs"):
            for item in os.listdir("outputs"):
                item_path = os.path.join("outputs", item)
                if os.path.isdir(item_path):
                    shutil.rmtree(item_path)
    except Exception as e:
        logger.warning(f"清空历史记录文件失败: {str(e)}")
    
    return True
